<template>
  <el-dialog :modelValue="visiable" title="新增项目" width="500" @close="$emit('closed')">
    <el-form :model="form" :rules="formRules" label-width="80px" :inline="false" class="mt-6" ref="ruleFormRef">
      <el-form-item label="项目名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入项目名称" />
      </el-form-item>

      <el-form-item label="项目简称" prop="shortName">
        <el-input v-model="form.shortName" placeholder="请输入项目简称" />
      </el-form-item>

      <el-form-item label="电压等级" prop="dianya">
        <el-select v-model="form.dianya" placeholder="请选择电压等级">
          <el-option label="220千伏" value="220千伏" />
          <el-option label="500千伏" value="500千伏" />
          <el-option label="750千伏" value="750千伏" />
          <el-option label="±800千伏" value="±800千伏" />
          <el-option label="1000千伏" value="1000千伏" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 立即创建 </el-button>
        <el-button @click="$emit('closed')">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import useProjState from '@/states/useProjStore'
import type { FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'

const { visiable } = defineProps<{
  visiable: Boolean
}>()
const emit = defineEmits(['closed'])

const ruleFormRef = ref()
const form = reactive<ProjDataInter>({
  name: '',
  shortName: '',
  dianya: '',
})
const formRules = ref<FormRules<ProjDataInter>>({
  name: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  shortName: [
    { required: true, message: '项目简称不能为空', trigger: 'blur' },
    { min: 3, max: 5, message: '长度必须为3-5位之间', trigger: 'blur' },
  ],
  dianya: [{ required: true, message: '电压等级不能为空' }],
})

const { add: addProj } = useProjState()

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await addProj(form)
      emit('closed')
    } else {
      console.log('error', fields)
    }
  })
}
</script>

<style></style>
